package com.my.kafka.demo;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

import java.time.Duration;
import java.util.Collections;
import java.util.Properties;

/**
 * 消费者
 */
public class ConsumerDemo {
    public static void main(String[] args) {
        //1.添加Kafka配置信息
        Properties pro = new Properties();

        //Kafka的连接地址
        pro.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"49.234.52.192:9092");
        //消费者组
        pro.put(ConsumerConfig.GROUP_ID_CONFIG,"group2");
        //消息key的反序列化器l
        pro.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringDeserializer");
        //消息value的反序列化器
        pro.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringDeserializer");
        //手动提交偏移量
        pro.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);

        //2.消费者对象
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(pro);

        //3.订阅主题
        consumer.subscribe(Collections.singletonList("tbug-topic-out"));

        //4.设置线程一种处于监听状态
        //同步提交和异步提交偏移量
        try {
            while(true) {
                //5.获取消息
                ConsumerRecords<String, String> messages = consumer.poll(Duration.ofMillis(1000)); //设置每秒钟拉取一次
                for (ConsumerRecord<String, String> message : messages) {
                    System.out.print(message.key() + ":");
                    System.out.println(message.value());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("记录错误的信息："+e);
        } finally {
            //同步
            consumer.commitSync();
        }

    }
}
